<template>
  <div class="my-cart" v-if="!cartloading">
    <h3 class="cart_head">
      购物车<span class="head_span"> （{{ cartlist?.length }}）</span>
    </h3>
    <div v-if="cartlist.length != []">
      <div class="card" v-for="(cart, index) in cartlist" :key="cart">
        <div class="left">
          <span class="radio_span">
            <input
              type="checkbox"
              class="checkboxitem"
              v-model="cart.checked"
              :checked="cart.checked"
            />
          </span>
          <span class="card_img_span">
            <img :src="cart.url" alt="" />
          </span>
        </div>
        <div class="cart-info">
          <span class="cart_name">{{ cart.name }}</span>
          <span class="cart_price">{{ cart.price }}</span>
          <span class="cart_goodnum">
            <span class="change_num_btn" @click="reduce(cart, index)">-</span>
            <span class="num_span">x {{ cart.goodnum }}</span>
            <span class="change_num_btn" @click="add(cart, index)">+</span>
          </span>
        </div>
        <span class="delete" @click="deletecart(cart, index)"
          ><el-icon><CloseBold /></el-icon
        ></span>
      </div>
    </div>
    <el-empty
      :image-size="200"
      description="暂无收藏的商品,快去添加吧~"
      v-else
    />
    <el-row class="bottom_pay_group">
      <el-col :span="4" class="total_col">
        <p>
          总计: <span>{{ alltotal }}</span>
        </p>
      </el-col>
      <el-col :span="4">
        <el-button @click="test" type="primary"
          ><el-icon><Money /></el-icon>立即支付</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getcartlist,
  request,
  pushcartlist,
  getuserinfo,
} from "network/request.js";
import { CloseBold, Money } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ElNotification } from "element-plus";
import { paymoney } from "untils/order.js";
export default {
  inject: ["reload"],
  data() {
    return {
      cartlist: [],
      newcartlist: [],
      cartloading: true,
      token: "",
      userid: "",
      checklist: [],
      total: 0,
      usernumber: "",
      computedtotal: 0,
    };
  },
  components: {
    CloseBold,
    Money,
  },
  computed: {
    //计算当前选中的商品总价
    alltotal: function () {
      var total = 0;
      for (let i = 0; i < this.cartlist.length; i++) {
        //如果选中则加入总价中
        if (this.cartlist[i].checked) {
          let price = parseInt(
            this.cartlist[i].price.split(" ")[1].split(",")[0]
          );
          total += price * this.cartlist[i].goodnum;
        }
      }
      return total;
    },
  },
  // watch: {
  //   checklist() {
  //     console.log(this.checklist)
  //     this.computedtotal = 0
  //     this.checklist.forEach(item => {
  //       let price = parseInt(item.price.split(' ')[1].split(',')[0])
  //       this.computedtotal += price * item.goodnum
  //     })
  //     // return this.computedtotal
  //   }
  // },
  async created() {
    this.token = localStorage.getItem("token");
    //获取用户的购物车信息
    await getcartlist(this.token).then(({ data: res }) => {
      this.userid = res[0].id;
      this.usernumber = res[0].usernumber;
      res[0].cartlist.forEach((item) => {
        //再次请求商品的详细信息并存入数组中
        request(item.goodid).then(({ data: response }) => {
          // this.newcartlist.push(item)
          item.url = response[0].dealswapperlist[0].url;
          item.name = response[0].carmessage.deal;
          item.price = response[0].carmessage.price;
          item.sets = response[0].sets;
          item.checked = false;
          this.cartlist.push(item);
        });
      });
      this.cartloading = false;
    });
  },
  methods: {
    //删除购物车商品数据
    deletecart(cart, index) {
      // console.log(cart,index)
      this.cartlist.splice(index, 1);
      getuserinfo(this.token).then(({ data: res }) => {
        this.userid = res[0].id;
        pushcartlist(this.userid, this.cartlist).then(() => {
          ElMessage.success("删除成功~");
        });
      });
    },
    reduce(cart, index) {
      // console.log(cart)
      if (this.cartlist[index].goodnum == 1) {
        return ElMessage.warning("无法继续减少啦~");
      }
      this.cartlist[index].goodnum--;
    },
    add(cart, index) {
      // console.log(cart)
      this.cartlist[index].goodnum++;
    },
    goodinfo(cart) {
      //返回单个商品对象
      let goodinfo = {
        goodid: cart.goodid,
        goodnum: cart.goodnum,
        price: cart.price,
      };
      return goodinfo;
    },
    test() {
      //计算所有选中商品总价 判断是否选中商品
      if (this.cartlist.some((item) => item.checked)) {
        this.total = 0;
        this.cartlist.forEach((item) => {
          if (item.checked) {
            let goodinfo = this.goodinfo(item);
            let price = item.price.split(" ")[1].split(",")[0];
            this.total += price * item.goodnum;
            this.checklist.push(goodinfo);
          }
        });
        paymoney(
          this.checklist,
          this.token,
          "",
          this.total,
          this.usernumber,
          "汽车购买"
        ).then(() => {
          this.cartlist.forEach((item, index) => {
            if (item.checked) {
              this.cartlist.splice(index, 1, "");
            }
          });
          ElNotification({
            title: "Success",
            message: "成功购买~",
            customClass: "cart-message",
            type: "success",
          });
          this.reload();
        });
      }else {
        ElNotification({
            title: "Warning",
            message: "请选择商品~",
            customClass: "cart-message",
            type: "warning",
          });
      }
    },
  },
  beforeUnmount() {
    //页面关闭时,保存当前用户的购物车信息
    pushcartlist(this.userid, this.cartlist);
  },
};
</script>

<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
}
a {
  color: blue;
}
span {
  color: #333;
}
.my-cart {
  width: 100%;
  height: calc(100vh - 10px);
  background-color: rgb(251, 251, 251);
  border-radius: 10px 10px 0 0;
  padding-top: 10px;
  overflow: auto;
  position: relative;
}
.cart_head {
  width: 90%;
  margin: 0 auto;
  height: 80px;
  line-height: 80px;
  letter-spacing: 2px;
  .head_span {
    font-size: 12px;
  }
}
.cart-info {
  height: 60%;
  display: flex;
  flex-direction: column;

  justify-content: space-around;
  span {
    text-align: right;
  }
  > .cart_name {
    color: #333;
    font-size: 24px;
    font-weight: 600;
  }
  > .cart_price {
    color: #333;
    font-size: 18px;
    font-weight: 500;
  }
  .cart_goodnum {
    font-size: 14px;
    color: #999;
    // background-color: #fff;
    > span {
      background-color: #fff;
      display: inline-block;
      box-sizing: border-box;
      height: 29px;
      line-height: 29px;
      padding: 0 5px;
      vertical-align: middle;
    }
    .num_span {
      color: #333;
    }
    .change_num_btn {
      width: 30px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      border: 1px solid #eee;
      color: #333;
      &:hover {
        background-color: #eee;
      }
    }
  }
}
.card {
  width: 90%;
  height: 150px;
  margin: 0 auto 10px;
  background-color: rgb(255, 241, 204);
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 20px;
  position: relative;
  .delete {
    position: absolute;
    right: 0;
    top: 0;
    width: 30px;
    height: 30px;
    // background-color: #fff;
    line-height: 30px;
    text-align: center;
    vertical-align: middle;
    border-radius: 50%;
    color: #333;
  }
  .left {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80%;
  }
  .radio_span {
    width: 30px;
    height: 30px;
    // background-color: green;
  }
  .card_img_span {
    // width: 130px;
    height: 100%;
    display: block;
    // background-color: yellow;
    img {
      width: 100%;
      height: 100%;
      vertical-align: top;
    }
  }
}
.card:hover {
  box-shadow: 0 0 10px rgb(238, 215, 153);
}
.bottom_pay_group {
  width: 100%;
  height: 10%;
  background-color: #fff;
  box-shadow: 0 -10px 20px #eee;
  position: absolute;
  display: flex;
  justify-content: end;
  bottom: 0;
  left: 0;
  .total_col {
    width: 100%;
    height: 100%;
    // background-color: red;
    display: flex;
    align-items: center;
    text-align: center;
    p {
      display: block;
      width: 100%;
      // background-color: yellow;
      font-size: 14px;
      font-family: "黑体";
      > span {
        font-size: 30px;
        font-weight: 600;
        font-family: "Times New Roman", Times, serif;
      }
    }
  }
  .el-button {
    height: 100%;
    width: 100%;
    display: block;
    // margin-left: 3px;
    background: linear-gradient(90deg, orange, red);
    font-size: 18px;
    font-weight: 600;
    border: none;
    letter-spacing: 4px;
  }
}
</style>